#!/usr/bin/env python

import gtk
import gobject
import gettext
import os
from signals import preferencesWindowSignals

gettext.install('blendIT','locale');

class preferencesWindow(gtk.Window):

   entries = {};
   
   # For sounds. Should be a better way to do this..
   translatable = {
      'buddy-online': _("Buddy Online: "),
      'buddy-offline': _("Buddy Offline: "),
      'buddy-message': _("Message Received: "),
      'buddy-invite': _("Invite Received: "),
      'buddy-received-file': _("File Received: "),
      'client-online': _("Client Online: "),
      'client-offline': _("Client Offline: "),
   };

   def __init__(self,blend):
      gtk.Window.__init__(self);
      self.set_title(_("Preferences"));
      self.set_icon_from_file("images/blendit.png");
      self.sigs = preferencesWindowSignals.signals(blend);
      self.blend = blend;


   def draw(self):
      notebook = gtk.Notebook();
      self.createPages(notebook);

      cancelButton = gtk.Button(stock=gtk.STOCK_CANCEL);
      cancelButton.connect('clicked',self.sigs.on_cancel);

      saveButton = gtk.Button(stock=gtk.STOCK_OK);
      saveButton.connect('clicked',self.sigs.on_save);

      hButtonBox = gtk.HButtonBox();
      hButtonBox.add(cancelButton);
      hButtonBox.add(saveButton);
      hButtonBox.show_all();

      vbox = gtk.VBox(spacing=8);
      vbox.pack_start(notebook,True,True);
      vbox.pack_start(hButtonBox);
      vbox.show_all();
      self.add(vbox);
      self.set_border_width(4);
      self.show();

   def createPages(self,notebook):
      self.createGeneralPage(notebook);
      self.createNotificationsPage(notebook);
      self.createAdvancedPage(notebook);


   def createNotificationsPage(self,notebook):
      page = gtk.Table(rows=2,columns=2);
      page.set_border_width(4);
      page.set_row_spacings(4);
      
      # Text
      self.entries['textNote'] = gtk.CheckButton(_("Text notifications"));
      try:
         import pynotify
         self.entries['textNote'].set_sensitive(True);
         if self.blend.config.notifications['text'] == True:
            self.entries['textNote'].set_active(True);
         else:
            self.entries['textNote'].set_active(False);
      except ImportError:
         self.entries['textNote'].set_sensitive(False);
         self.entries['textNote'].set_active(False);

      page.attach(self.entries['textNote'],0,1,0,1,gtk.FILL);

      # Sound
      self.entries['soundNote'] = gtk.CheckButton(_("Sounds"));
      try:
         import audiere
         self.entries['soundNote'].set_sensitive(True);
      except ImportError:
         self.entries['soundNote'].set_sensitive(False);
         self.entries['soundNote'].set_active(False);

      if self.blend.config.notifications['sounds'][0] == True:
         self.entries['soundNote'].set_active(True);
      else:
         self.entries['soundNote'].set_active(False);

      self.entries['sounds'] = [];
      rows = self.blend.config.notifications['sounds'][1].keys();
      table = gtk.Table(rows=len(rows),columns=2);
      for i in range(0,len(rows)):
         value = self.blend.config.notifications['sounds'][1][rows[i]];
         try:
            nameLabel = gtk.Label(self.translatable[rows[i]]);
         except:
            nameLabel = gtk.Label(rows[i]);
         nameLabel.set_alignment(1,0.5);
         valueEntry = gtk.Entry();
         valueEntry.set_text(value);
         valueEntry.show();
         self.entries['sounds'].append((valueEntry,rows[i]));
         
         table.attach(nameLabel,0,1,i,i+1,gtk.FILL);
         table.attach(valueEntry,1,2,i,i+1,gtk.FILL,gtk.EXPAND);

      table.set_row_spacings(4);
      table.set_col_spacings(4);
      page.attach(self.entries['soundNote'],0,1,1,2,gtk.FILL);
      page.attach(table,1,2,1,2,gtk.FILL,gtk.EXPAND);

      # Label      
      label = gtk.Label(_("Notifications"));
      label.show();
      page.show_all();
      notebook.append_page(page,label);


   def createAdvancedPage(self,notebook):
      page = gtk.Table(rows=4,columns=2);
      page.set_row_spacings(4);
      page.set_border_width(4);
      
      # server details
      self.entries['serverHost'] = gtk.Entry();
      self.entries['serverHost'].set_text(self.blend.config.host);
      self.entries['serverHost'].show();
      self.entries['serverPort'] = gtk.Entry();
      self.entries['serverPort'].set_text(str(self.blend.config.port));
      self.entries['serverPort'].show();
      self.entries['serverPort'].set_width_chars(5);
      self.entries['serverPort'].set_max_length(5);
      hbox = gtk.HBox();
      hbox.pack_start(self.entries['serverHost']);
      hbox.pack_start(self.entries['serverPort']);
      hbox.show_all();
      page.attach(gtk.Label(_("Server/Port: ")),0,1,0,1,gtk.FILL);
      page.attach(hbox,1,2,0,1,gtk.FILL);


      # Time format
      self.entries['timeFormat'] = gtk.Entry();
      self.entries['timeFormat'].set_text(self.blend.config.timeformat);
      self.entries['timeFormat'].show();
      page.attach(gtk.Label(_("Time/Date Format: ")),0,1,1,2,gtk.FILL);
      page.attach(self.entries['timeFormat'],1,2,1,2,gtk.FILL);

      page.attach(gtk.Label(_("%H - Hour (0-24), %I - Hour (1-12), %P - am/pm, %M - Minute, %S - Second\n%d - Day, %m - Month, %Y - Year")),1,2,2,3,gtk.FILL);

      # Debug Mode
      self.entries['debugMode'] = gtk.CheckButton(_("Enable Debug Mode"));
      if self.blend.config.debug == True:
         self.entries['debugMode'].set_active(True);

      page.attach(self.entries['debugMode'],0,1,3,4,gtk.FILL);
      infoLabel = gtk.Label(_("(Requires BlendIt to be restarted)"));
      infoLabel.set_alignment(0,0.5);
      page.attach(infoLabel,1,2,3,4,gtk.FILL);

      # Label      
      label = gtk.Label(_("Advanced"));
      label.show();
      page.show_all();
      notebook.append_page(page,label);



   def createGeneralPage(self,notebook):
      page = gtk.Table(rows=7,columns=2);
      page.set_row_spacings(4);

      # alias
      self.entries['alias'] = gtk.Entry();
      if self.blend.currentAccount.alias == "":
         self.blend.currentAccount.alias = "Me";
      self.entries['alias'].set_text(self.blend.currentAccount.alias);
      self.entries['alias'].show();
      aliasLabel = gtk.Label(_("Alias: "));
      aliasLabel.set_alignment(1,0.5);
      hbox = gtk.HBox();
      hbox.pack_start(self.entries['alias']);
      hbox.pack_start(gtk.Label(_(" (What you see in your chat window)")));
      hbox.show_all();
      page.attach(aliasLabel,0,1,0,1,gtk.FILL);
      page.attach(hbox,1,2,0,1,gtk.FILL);


      # log message locally
      self.entries['log'] = gtk.CheckButton(_("Log messages locally"));
      if self.blend.config.log == True:
         self.entries['log'].set_active(True);
      else:
         self.entries['log'].set_active(False);
      page.attach(self.entries['log'],1,2,1,2,gtk.FILL);


      # hide offline
      self.entries['hideOffline'] = gtk.CheckButton(_("Hide offline contacts"));
      if self.blend.config.hideOfflineContacts == True:
         self.entries['hideOffline'].set_active(True);
      else:
         self.entries['hideOffline'].set_active(False);
      page.attach(self.entries['hideOffline'],1,2,2,3,gtk.FILL);


      # offline message / goodbye message
      self.entries['offlineMsg'] = gtk.Entry();
      self.entries['offlineMsg'].set_text(self.blend.config.offlineMessage[1]);
      self.entries['offlineMsg'].show();
      
      self.entries['offlineMsgEnable'] = gtk.CheckButton(_("Goodbye message: "));
      self.entries['offlineMsgEnable'].connect('toggled',self.sigs.offlineMsgEnable);

      if self.blend.config.offlineMessage[0] == False:
         self.entries['offlineMsg'].set_sensitive(False);
         self.entries['offlineMsgEnable'].set_active(False);
      else:
         self.entries['offlineMsg'].set_sensitive(True);
         self.entries['offlineMsgEnable'].set_active(True);

      hbox = gtk.HBox();
      hbox.pack_start(self.entries['offlineMsg']);
      hbox.pack_start(gtk.Label(_("(Markup is supported)")));
      hbox.show_all();
      omAlign = gtk.Alignment(xalign=1,yalign=0.5);
      omAlign.add(self.entries['offlineMsgEnable']);
      omAlign.show_all();
      page.attach(omAlign,0,1,3,4,gtk.FILL);
      page.attach(hbox,1,2,3,4,gtk.FILL);

      
      # auto away
      adjust = gtk.Adjustment(float(self.blend.config.autoAway[1]),lower=0,upper=30,step_incr=1,page_incr=5);
      self.entries['autoAway'] = gtk.SpinButton(adjust);
      self.entries['autoAway'].set_update_policy(gtk.UPDATE_IF_VALID);
      #self.entries['autoAway'].set_value(float(self.blend.config.autoAway[1]));
      self.entries['autoAway'].show();
      
      self.entries['autoAwayEnable'] = gtk.CheckButton(_("Auto Away: "));
      self.entries['autoAwayEnable'].connect('toggled',self.sigs.autoAwayEnable);

      if self.blend.config.offlineMessage[0] == False:
         self.entries['autoAway'].set_sensitive(False);
         self.entries['autoAwayEnable'].set_active(False);
      else:
         self.entries['autoAway'].set_sensitive(True);
         self.entries['autoAwayEnable'].set_active(True);

      aaAlign = gtk.Alignment(xalign=1,yalign=0.5);
      aaAlign.add(self.entries['autoAwayEnable']);
      aEntryAlign = gtk.Alignment(xalign=0,yalign=0.5);
      aEntryAlign.add(self.entries['autoAway']);
      aEntryAlign.show_all();
      page.attach(aaAlign,0,1,4,5,gtk.FILL);
      page.attach(aEntryAlign,1,2,4,5,gtk.FILL);


      # Language
      model = gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING);
      # Hard coded for now...
      model.append(('English','en'));
      model.append(('Afrikaans','af'));
      model.append(('Other','en')); # Means no translation
      self.entries['language'] = gtk.ComboBox(model);

      txt = gtk.CellRendererText();
      self.entries['language'].pack_start(txt,True);
      self.entries['language'].add_attribute(txt,'text',0);
      
      # Yes.. yes, I know shut up
      if self.blend.currentAccount.lang == "en":
         self.entries['language'].set_active(0);
      elif self.blend.currentAccount.lang == "af":
         self.entries['language'].set_active(1);
      else:
         self.entries['language'].set_active(2);
      
      langLabel = gtk.Label(_("Language: "));
      langLabel.set_alignment(1,0.5);
      langAlign = gtk.Alignment(xalign=0,yalign=0.5);
      langAlign.add(self.entries['language']);
      langAlign.show_all();
      page.attach(langLabel,0,1,5,6);
      page.attach(langAlign,1,2,5,6);

      # persistant message colour
      self.entries['msgColourEnable'] = gtk.CheckButton(_("Message Colour: "));
      self.entries['msgColourEnable'].connect('toggled',self.sigs.msgColourEnable);
      
      self.entries['msgColour'] = colourButton = gtk.ColorButton();
      self.entries['msgColour'].set_use_alpha(False);

      if self.blend.config.msgColour[0] == False:
         self.entries['msgColour'].set_sensitive(False);
         self.entries['msgColourEnable'].set_active(False);
         self.entries['msgColour'].set_color(gtk.gdk.Color(0,0,0));
      else:
         try:
            self.entries['msgColour'].set_color(gtk.gdk.color_parse(self.blend.config.msgColour[1]));
         except ValueError:
            pass; # Hmmmmm
         self.entries['msgColour'].set_sensitive(True);
         self.entries['msgColourEnable'].set_active(True);

      self.entries['msgColour'].set_title(_("Message Colour"));
     

      colAlign = gtk.Alignment(xalign=0,yalign=0.5);
      colAlign.add(self.entries['msgColour']);
      colAlign.show_all();
      coleAlign = gtk.Alignment(xalign=1,yalign=0.5);
      coleAlign.add(self.entries['msgColourEnable']);
      coleAlign.show_all();
      page.attach(coleAlign,0,1,6,7,gtk.FILL);
      page.attach(colAlign,1,2,6,7,gtk.FILL);

      label = gtk.Label(_("General"));
      label.show();
      page.show_all();
      notebook.append_page(page,label);